package cn.darkbox.sdk.zpdf;

import static cn.darkbox.sdk.zpdf.Utils.view2Bitmap;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.pdf.PdfDocument;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * PDFView 组件
 * 提供PDF文档的预览和导出功能，支持添加文字和图片，具有智能分页功能
 */
public class PDFView extends FrameLayout {
    // PDF构建器，用于实时预览
    private LinearLayout pdfBuilder;
    // PDF预览器，显示预览内容
    private LinearLayout pdfPreviewer;
    // PDF预览器Root
    private View rootV;

    // PDF配置信息
    private PDFConfig pdfConfig = new PDFConfig();
    // 线程池，用于异步处理PDF导出
    private ExecutorService executorService;
    // 构建任务的Future对象，用于取消任务
    private Future<?> buildFuture;
    // 存储所有添加的内容信息
    private List<ContentInfo> contentInfos = new ArrayList<>();
    // 主线程Handler，用于在UI线程更新预览
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    // 预览回调接口
    private Callback previewCallback;

    /**
     * 构造方法
     */
    public PDFView(@NonNull Context context) {
        super(context);
        init();
    }

    public PDFView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PDFView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 初始化PDFView组件
     * 创建预览布局和设置基本参数
     */
    private void init() {
        executorService = Executors.newSingleThreadExecutor();
        LayoutInflater.from(getContext()).inflate(R.layout.ui_pdf_view, this, true);
        pdfBuilder = findViewById(R.id.pdf_builder);
        pdfPreviewer = findViewById(R.id.pdf_preview);
        rootV = findViewById(R.id.root);

        GradientDrawable drawable = new GradientDrawable();
        drawable.setSize(1, Utils.dip2px(getContext(), 10));
        pdfPreviewer.setDividerDrawable(drawable);
        pdfPreviewer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
    }

    /**
     * 设置PDF页面大小
     * @param width 页面宽度（像素）
     * @param height 页面高度（像素）
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView setPageSize(int width, int height) {
        this.pdfConfig.pageWidth = width;
        this.pdfConfig.pageHeight = height;
        return this;
    }

    /**
     * 设置页面内边距
     * @param pagePadding 边距矩形对象，定义四周的内边距
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView setPagePadding(Rect pagePadding) {
        this.pdfConfig.pageOffset = pagePadding;
        return this;
    }

    /**
     * 设置页面背景颜色
     * @param color 颜色值
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView setPageColor(int color) {
        this.pdfConfig.pageColor = color;
        return this;
    }

    /**
     * 设置文本样式
     * @param color 文本颜色
     * @param size 文本大小
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView setTextStyle(int color, int size) {
        this.pdfConfig.textColor = color;
        this.pdfConfig.textSize = size;
        return this;
    }

    /**
     * 重置所有内容
     * 清除已添加的所有文本和图片
     */
    public void reset() {
        contentInfos.clear();
        pdfBuilder.removeAllViews();
        pdfPreviewer.removeAllViews();
        pdfConfig.pdfPageBitmaps.clear();
    }

    /**
     * 添加文本内容
     * 支持自动分页和段落完整性
     * @param text 要添加的文本
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView addText(String text) {
        addText(text, Color.BLACK, Utils.sp2px(getContext(), 16));
        return this;
    }

    /**
     * 添加带样式的文本内容
     * @param text 要添加的文本
     * @param color 文本颜色
     * @param size 文本大小
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView addText(String text, int color, int size) {
        ContentInfo contentInfo = new ContentInfo(text, ContentInfo.ContentType_TEXT);
        contentInfo.textColor = color;
        contentInfo.textSize = size;
        contentInfos.add(contentInfo);
        return this;
    }

    /**
     * 添加网络图片
     * 支持自动分页，确保图片完整性
     * @param img 图片URL
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView addImage(String img) {
        contentInfos.add(new ContentInfo(img, ContentInfo.ContentType_IMG));
        return this;
    }

    private int getImgContentCount() {
        int count = 0;
        for (ContentInfo contentInfo : contentInfos) {
            if (contentInfo.type == ContentInfo.ContentType_IMG) {
                count++;
            }
        }
        return count;
    }

    private void initPdfInfo() {

        if (pdfConfig.pageWidth == 0) {
            pdfConfig.pageWidth = pdfBuilder.getWidth();
        }

        if (pdfConfig.pageHeight == 0) {
            pdfConfig.pageHeight = rootV.getHeight();
        }

        if (pdfConfig.scale == 1) {
            pdfConfig.scale = pdfBuilder.getWidth() * 1f / pdfConfig.pageWidth;
        }
    }

    private int textSize(ContentInfo contentInfo) {
        return contentInfo.textSize != 0
                ? contentInfo.textSize
                : pdfConfig.textSize != 0 ? pdfConfig.textSize : Utils.sp2px(getContext(), 16);
    }

    private int textColor(ContentInfo contentInfo) {
        return contentInfo.textColor != 0
                ? contentInfo.textColor
                : pdfConfig.textColor != 0 ? pdfConfig.textColor : Color.BLACK;
    }

    /**
     * 设置预览回调
     * @param previewCallback 回调接口
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView setPreviewCallback(Callback previewCallback) {
        this.previewCallback = previewCallback;
        return this;
    }

    /**
     * 显示或更新预览
     * 在添加内容后调用此方法刷新预览
     */
    public void showOrUpdate() {
        if(this.previewCallback != null) {
            this.previewCallback.onStart();
        }
        if (pdfBuilder.getWidth() == 0) {
            pdfBuilder.post(() -> {
                doRefreshPDF();
            });
        } else {
            doRefreshPDF();
        }
    }

    private void doRefreshPDF() {
        initPdfInfo();
        pdfBuilder.removeAllViews();
        int imgContentCount = getImgContentCount();
        final int[] imgContentLoadedCount = {0};
        for (int i = 0; i < contentInfos.size(); i++) {
            View childV;
            ContentInfo contentInfo = contentInfos.get(i);
            if (contentInfo.type == ContentInfo.ContentType_IMG) {
                ImageView imageView = new ImageView(getContext());
                imageView.setAdjustViewBounds(true);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);

                RequestBuilder<Drawable> requestBuilder;
                if (contentInfo.imgD != null) {
                    requestBuilder = Glide.with(PDFView.this).load(contentInfo.imgD);
                } else {
                    requestBuilder = Glide.with(PDFView.this).load(contentInfo.content);
                }
                requestBuilder.addListener(new RequestListener<Drawable>() {

                    void doRefreshPdf() {
                        if (imgContentLoadedCount[0] == imgContentCount) {
                            initPDFPreview();
                        }
                    }

                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        imgContentLoadedCount[0]++;
                        doRefreshPdf();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        imgContentLoadedCount[0]++;
                        doRefreshPdf();
                        return false;
                    }
                }).into(imageView);

                childV = imageView;
            } else {
                TextView textView = new TextView(getContext());
                textView.setText(contentInfo.content);
                textView.setTextColor(textColor(contentInfo));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize(contentInfo));
                childV = textView;
            }
            childV.setPadding(pdfConfig.getPaddingL(), 0, pdfConfig.getPaddingR(), 0);
            pdfBuilder.addView(childV, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }

        if (imgContentCount <= 0) {
            initPDFPreview();
        }
    }

    /**
     * 添加Drawable图片
     * @param img Drawable对象
     * @return 当前PDFView实例，支持链式调用
     */
    public PDFView addImage(Drawable img) {
        contentInfos.add(new ContentInfo(img));
        return this;
    }

    private void initPDFPreview() {
        Utils.executeOnPreDrawListener(pdfBuilder, () -> {
            initPDFPageInfo();
            pdfPreviewer.removeAllViews();

            for (int i = 0; i < pdfConfig.pdfPageBitmaps.size(); i++) {
                PDFPageBitmap section = pdfConfig.pdfPageBitmaps.get(i);

                FrameLayout pageLayout = new FrameLayout(getContext());
                pageLayout.setBackgroundColor(pdfConfig.pageColor);


                ImageView pageBGLayout = new ImageView(getContext());
                pageBGLayout.setScaleType(ImageView.ScaleType.CENTER_CROP);


                pageLayout.addView(pageBGLayout, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

                ImageView contentV = new ImageView(getContext());
                contentV.setImageBitmap(section.content);
                contentV.setScaleType(ImageView.ScaleType.FIT_CENTER);
                contentV.setPadding(0, pdfConfig.getPaddingT(), 0, pdfConfig.getPaddingB());

                pageLayout.addView(contentV, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, pdfConfig.getPreviewHeight());

                pdfPreviewer.addView(pageLayout, lp);
            }

            if(this.previewCallback != null) {
                this.previewCallback.onCompleted();
            }
        });
        pdfBuilder.requestLayout();
    }


    private void initPDFPageInfo() {
        int totalEnd = 0;
        pdfConfig.pdfPageBitmaps.clear();
        do {
            int start = totalEnd;
            int end = start + pdfConfig.getPreviewPageContentHeight();
            PDFPageBitmap section = new PDFPageBitmap();
            pdfConfig.pdfPageBitmaps.add(section);

            if (end > pdfBuilder.getTop()) {
                int endInContentLayout = end - pdfBuilder.getTop();

                for (int i = 0; i < pdfBuilder.getChildCount(); i++) {
                    View childAt = pdfBuilder.getChildAt(i);

                    if (childAt.getBottom() > endInContentLayout) {
                        if (childAt.getTop() < endInContentLayout) {//落到了这个view中间
                            if (childAt instanceof TextView) {
                                int endInTextView = endInContentLayout - childAt.getTop();

                                int lineNumEnd = ((TextView) childAt).getLayout().getLineForVertical(endInTextView);
                                lineNumEnd = Math.min(lineNumEnd, ((TextView) childAt).getLineCount() - 1);

                                if (endInTextView < ((TextView) childAt).getLayout().getLineBottom(lineNumEnd)) {
                                    endInTextView = ((TextView) childAt).getLayout().getLineTop(lineNumEnd);
                                }

                                endInContentLayout = childAt.getTop() + endInTextView;
                            } else {
                                if (pdfConfig.getPreviewPageContentHeight() >= childAt.getHeight()) { //下一页能完全放下这个图片
                                    endInContentLayout = childAt.getTop();
                                }
                            }
                        }
                        break;
                    }
                }

                end = endInContentLayout + pdfBuilder.getTop();

                end = Math.min(end, pdfBuilder.getHeight());
            }

            section.content = view2Bitmap(pdfBuilder, start, end);
            totalEnd = end;

        } while (totalEnd < pdfBuilder.getHeight());
    }


    /**
     * 导出PDF文件
     * @param targetFile 目标文件
     * @param callback 导出过程回调
     */
    public void export(File targetFile, Callback callback) {

        mainHandler.post(() -> {
            if (callback != null) {
                callback.onStart();
            }
        });

        buildFuture = executorService.submit(() -> {
            try {
                PdfDocument document = new PdfDocument();

                for (int i = 0; i < pdfConfig.pdfPageBitmaps.size(); i++) {
                    PDFPageBitmap section = pdfConfig.pdfPageBitmaps.get(i);

                    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
                            pdfConfig.pageWidth,
                            pdfConfig.pageHeight, i + 1)
                            .create();

                    PdfDocument.Page page = document.startPage(pageInfo);

                    Canvas canvas = page.getCanvas();
                    canvas.drawColor(pdfConfig.pageColor);

                    canvas.save();
                    canvas.translate(0, pdfConfig.pageOffset.top);

                    Matrix matrix = new Matrix();
                    matrix.postScale(1f / pdfConfig.scale, 1f / pdfConfig.scale, 0, 0);
                    canvas.drawBitmap(section.content, matrix, null);

                    canvas.restore();

                    document.finishPage(page);
                }

                Utils.createDirectory(targetFile.getParent());

                try (FileOutputStream os = new FileOutputStream(targetFile)) {
                    document.writeTo(os);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    document.close();
                }

                mainHandler.post(() -> {
                    if (callback != null) {
                        callback.onCompleted();
                    }
                });

            } catch (Exception e) {
                mainHandler.post(() -> {
                    if (callback != null) {
                        callback.onError(e);
                    }
                });
            }
        });
    }

    /**
     * 组件销毁时清理资源
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        try {
            if (buildFuture != null && !buildFuture.isCancelled()) {
                buildFuture.cancel(true);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 回调接口
     * 用于处理预览和导出过程的事件
     */
    public interface Callback {
        // 开始处理时调用
        default void onStart() {
        }

        // 处理完成时调用
        default void onCompleted() {
        }

        // 发生错误时调用
        default void onError(Throwable throwable) {
        }
    }
}
